<?php
namespace app\common\service;

use EasyWeChat\Factory;
use GuzzleHttp\Client;

// 企业微信，文档管理类
class WorkWechatSheet{

    protected $app = null;
    protected $corp_id = null;
    protected $agent_id = null;
    protected $secret = null;
    protected $httpClient = null;
    

    public function __construct()
    {   
        $config = [
            'corp_id' => 'wwb6dbb7fcd530ad52',
            'agent_id' => 1000002,
            'secret'   => 'ZVw0RNIZX_GUkoQYjSJgsc4BgmSaAiyc3XVMp9IbL28',
            // server config
            // 'token' => 'xxxxxxxxx',
            // 'aes_key' => 'xxxxxxxxxxxxxxxxxx',
        
            //...
        ];
        $this->corp_id = $config['corp_id'];
        $this->agent_id = $config['agent_id'];
        $this->secret = $config['secret'];

        $this->httpClient = new Client();
        
    }


    public function getAccessToken(){
        $url = sprintf("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s", $this->corp_id, $this->secret);
        $token_data = $this->openRequest($url);
        return $token_data['access_token'];
    }


    // 创建文档

    // 读取文档数据

    public function getSheetData(){
        $access_token = $this->getAccessToken();
        $url =sprintf("https://qyapi.weixin.qq.com/cgi-bin/wedoc/spreadsheet/get_sheet_properties?access_token=%s", $access_token);
        $result =  $this->openRequest($url, 'POST', [], 'array', [
            'json' => [
                'docid' => 'dc4DjdKVuVa3LsObCuETEbFcjUrwY2arkL2ZjUfY4HR7KBVztXz9d7INVKIoA6KttE9D-1YP32pXil9fzjUdAvfA'
            ]
        ]);
        dump($result);
    }

    // 创建一个文档
    public function createDocSheet(){
        $access_token = $this->getAccessToken();
        $url =sprintf("https://qyapi.weixin.qq.com/cgi-bin/wedoc/create_doc?access_token=%s", $access_token);
        $result =  $this->openRequest($url, 'POST', [], 'array', [
            'json' => [
                "doc_type" =>  "4",
                "doc_name" =>  "林斌-论文辅导名单",
                "admin_users" => ['LiuTianPeng']
            ]
        ]);
        dump($result);
    }

    
    public function openRequest($url = '', $methods = 'GET', $form_params = [], $return = 'array', $option = [], $reflash_proxy = false, $time = 1)
    {
        $result = false;

        try {
            $response = $this->httpClient->request(
                $methods,
                $url,
                $option
            );
            $contents = $response->getBody()->getContents();
            $result = $return == 'array' ? json_decode($contents, true) : $contents;
            // dump($result);
        } catch (\GuzzleHttp\Exception\ConnectException $e) {
            // 链接失败、重试,
            $result = false;
        }


        return $result;
    }
 
    
}